package mysql

import (
	"time"

	"douyin/models"
	"douyin/utils/pkg/snowflake"

	"gorm.io/gorm"
)

// InsertComment 创建一条评论
func InsertComment(content string) (commentId int64, err error) {
	//1.生成commentId
	commentId = snowflake.GenID()
	//2.填入内容
	com := &models.Com{
		Id:      commentId,
		Content: content,
	}
	//3.插入数据库
	tx := db.Debug().Model(&models.Com{}).Create(com)
	if tx.Error != nil {
		return 0, tx.Error
	}
	return
}

// DeleteComment 删除一条评论
func DeleteComment(commentId int64) (err error) {
	tx := db.Debug().Model(&models.Com{}).Where("comment_id = ?", commentId).Delete(nil)
	if tx.RowsAffected == 0 {
		return ErrorDeleteFailed
	}
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// SelectComment 查询一条评论
func SelectComment(commentId int64) (comment models.Com, err error) {
	tx := db.Debug().Model(&models.Com{}).Where("comment_id = ?", commentId).First(&comment)
	if tx.Error == gorm.ErrRecordNotFound {
		err = ErrorQueryZeroRecord
		return
	}
	if tx.Error != nil {
		err = tx.Error
		return
	}
	return
}

// InsertCommentator 插入评论关系
func InsertCommentator(videoId, commentId, userId int64) (err error) {
	p := &models.Commentator{
		UserId:    userId,
		VideoId:   videoId,
		CommentId: commentId,
	}
	tx := db.Debug().Model(&models.Commentator{}).Create(p)
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// DeleteCommentator 删除评论关系
func DeleteCommentator(videoId, commentId, userId int64) (err error) {
	tx := db.Debug().Model(&models.Commentator{}).Where("video_id = ? AND comment_id = ? AND user_id = ?", videoId, commentId, userId).Delete(nil)
	if tx.RowsAffected == 0 {
		return ErrorDeleteFailed
	}
	if tx.Error != nil {
		return tx.Error
	}
	return
}

// SelectCommentator 查找到数据，按发布时间:从早到晚 返回
func SelectCommentator(videoId int64) (commentatorIds []models.CommentatorResult, err error) {
	tx := db.Debug().Model(&models.Commentator{}).Select("comment_id", "user_id").Where("video_id=?", videoId).Order("create_time").Find(&commentatorIds)
	if tx.RowsAffected == 0 {
		return nil, ErrorQueryZeroRecord
	}
	if tx.Error != nil {
		return nil, tx.Error
	}
	return
}

// CombiComment 组合返回评论列表
func CombiComment(commentatorIds []models.CommentatorResult, userId int64) (commentList []models.Comment, err error) {

	for _, v := range commentatorIds {
		com, err1 := SelectComment(v.CommentId)
		if err1 != nil {
			err = err1
			return
		}
		user, err2 := SelectUserByUserId(v.UserId)
		if err2 != nil {
			err = err2
			return
		}
		//查找用户和我的关系
		follow := WhetherFollow(userId, user.Id)
		user.IsFollow = follow
		//时间格式化
		createDate := TimeFormat(com.CreateTime)
		temp := models.Comment{
			Id:         com.Id,
			User:       user,
			Content:    com.Content,
			CreateDate: createDate,
		}
		commentList = append(commentList, temp)
	}
	return
}

// VideoCommentCount 维护某一个视频的评论总数
func VideoCommentCount(videoId int64, isAdd bool) (err error) {
	var str string
	var condition string
	if isAdd {
		str = "+"
		condition = ""
	} else {
		str = "-"
		condition = " AND comment_count>0"
	}
	tx := db.Debug().Model(&models.Vid{}).Where("video_id = ?"+condition, videoId).Update("comment_count", gorm.Expr("comment_count"+str+" ?", 1))
	if tx.RowsAffected == 0 {
		err = ErrorUpdateFailed
		return
	}
	if tx.Error != nil {
		err = tx.Error
		return
	}
	return
}

func TimeFormat(timeStamp int64) (createDate string) {
	timeLayout := "01-02"
	dateTime := time.Unix(timeStamp, 0).Format(timeLayout)
	//fmt.Printf("After Format: %v\n", dateTime)
	return dateTime
}
